<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>机票订购 - ${flight.flightId}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-blue: #3498db;
            --dark-blue: #2980b9;
            --light-blue: #e3f2fd;
        }

        body {
            background: url('img/login_background.png') no-repeat center center fixed;
            background-size: cover;
            min-height: 100vh;
            padding-top: 80px;
        }

        .flight-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
            max-width: 1000px;
            margin: 2rem auto;
            overflow: hidden;
        }

        .seat-select-wrapper {
            position: relative;
            margin: 1rem 0;
        }

        .seat-input {
            width: 100%;
            padding: 1rem;
            border: 2px solid #dee2e6;
            border-radius: 12px;
            cursor: pointer;
            background: white url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e") right 1rem center/16px 12px no-repeat;
            transition: all 0.3s ease;
        }

        .seat-dropdown {
            position: absolute;
            width: 100%;
            background: white;
            border-radius: 12px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
            padding: 1.5rem;
            z-index: 1000;
            margin-top: 0.5rem;
            display: none;
        }

        .seat-grid {
            display: grid;
            grid-template-columns: repeat(8, 1fr);
            gap: 0.8rem;
        }

        .seat-item {
            padding: 0.8rem;
            text-align: center;
            border-radius: 8px;
            cursor: pointer;
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            transition: all 0.2s ease;
        }

        .seat-item:hover {
            transform: translateY(-2px);
            border-color: var(--primary-blue);
            background: var(--light-blue);
        }

        .seat-item.selected {
            background: var(--primary-blue);
            color: white;
            border-color: var(--dark-blue);
        }

        .seat-item.occupied {
            background: #f8d7da !important;
            border-color: #dc3545 !important;
            opacity: 0.7;
            pointer-events: none;
        }

        .selected-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-top: 1.5rem;
            display: none;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .info-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.8rem;
        }

        .info-label {
            color: #6c757d;
            font-weight: 500;
        }

        .info-value {
            color: #2c3e50;
            font-weight: 600;
        }

        .price-display {
            font-size: 2rem;
            color: var(--primary-blue);
            margin: 1.5rem 0;
            padding: 1rem;
            background: rgba(52, 152, 219, 0.1);
            border-radius: 12px;
            transition: all 0.3s ease;
            animation: pricePulse 1.5s ease-in-out;
        }

        @keyframes pricePulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }

        .class-option {
            transition: all 0.3s ease;
            cursor: pointer;
            border: 2px solid transparent;
        }

        .class-option:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 15px rgba(0,0,0,0.1);
        }

        .class-option.active {
            border-color: var(--primary-blue);
            background: var(--light-blue);
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <div class="flight-card">
            <div class="p-4 border-bottom">
                <div class="d-flex justify-content-between align-items-center">
                    <h2 class="mb-0">${flight.flightId}</h2>
                    <div class="badge bg-primary">${flight.aircraftId}</div>
                </div>
            </div>

            <div class="p-4">
                <div class="row g-4 mb-4">
                    <div class="col-md-6">
                        <div class="card h-100 border-0 shadow-sm">
                            <div class="card-body">
                                <h5 class="card-title text-primary mb-3">🛫 出发信息</h5>
                                <div class="display-6 mb-2">${flight.origin}</div>
                                <div class="text-muted">
                                    ${fn:replace(fn:substring(flight.departureTime.toString(), 0, 16), 'T', ' ')}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card h-100 border-0 shadow-sm">
                            <div class="card-body">
                                <h5 class="card-title text-danger mb-3">🛬 到达信息</h5>
                                <div class="display-6 mb-2">${flight.destination}</div>
                                <div class="text-muted">
                                    ${fn:replace(fn:substring(flight.arrivalTime.toString(), 0, 16), 'T', ' ')}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="configurator p-4 border rounded-3">
                    <div class="mb-4">
                        <h5 class="mb-3">选择舱位类型</h5>
                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="class-option p-3 rounded-3 active" data-class="economy">
                                    <h5>经济舱</h5>
                                    <div class="h4 text-success">¥${flight.price}</div>
                                    <small class="text-muted">基础价格</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="class-option p-3 rounded-3" data-class="business">
                                    <h5>商务舱</h5>
                                    <div class="h4 text-success">¥${flight.price * 1.5}</div>
                                    <small class="text-muted">1.5倍价格</small>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="class-option p-3 rounded-3" data-class="first">
                                    <h5>头等舱</h5>
                                    <div class="h4 text-success">¥${flight.price * 3}</div>
                                    <small class="text-muted">3倍价格</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <h5 class="mb-3">选择座位号</h5>
                        <div class="seat-select-wrapper">
                            <input type="text" 
                                   class="seat-input" 
                                   id="seatInput"
                                   placeholder="点击选择座位（1-40）"
                                   readonly
                                   required>
                            <div class="seat-dropdown" id="seatDropdown">
                                <div class="seat-grid" id="seatGrid"></div>
                            </div>
                        </div>
                        <small class="text-muted d-block mt-2">红色座位表示已被预订</small>
                    </div>

                    <div class="selected-card" id="selectedCard">
                        <h5 class="mb-3">🎫 您的选择</h5>
                        <div class="info-item">
                            <span class="info-label">座位号：</span>
                            <span class="info-value" id="displaySeat">-</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">舱位类型：</span>
                            <span class="info-value" id="displayClass">-</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">票面价格：</span>
                            <span class="info-value" id="displayPrice">-</span>
                        </div>
                    </div>


                    <form action="OrderFlightServlet" method="post" onsubmit="return validateForm()">
                        <input type="hidden" name="flightId" value="${flight.flightId}">
                        <input type="hidden" name="classType" id="selectedClass" value="economy">
                        <input type="hidden" name="finalPrice" id="finalPriceValue" value="${flight.price}">
                        <input type="hidden" name="seatNumber" id="selectedSeat">
                        
                        <button type="submit" class="btn btn-primary btn-lg w-100 py-3">
                            立即预订 → 
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 初始化座位
        function initSeats() {
            const grid = document.getElementById('seatGrid');
            grid.innerHTML = '';
            
            // 模拟已占座位（实际应从后端获取）
            const occupiedSeats = [3, 5, 7, 15, 22, 25]; 
            
            for(let i = 1; i <= 40; i++) {
                const seat = document.createElement('div');
                seat.style.caretColor = "transparent"
                seat.className = 'seat-item' + (occupiedSeats.includes(i) ? ' occupied' : '');
                seat.textContent = i;
                
                if(occupiedSeats.includes(i)) {
                    seat.innerHTML = `
                        ${i}
                        <small class="d-block text-danger">已选</small>
                    `;
                    seat.style.pointerEvents = 'none';
                }
                
                seat.onclick = () => {
                    if(!occupiedSeats.includes(i)) selectSeat(i);
                };
                grid.appendChild(seat);
            }
        }

        // 选择座位
        function selectSeat(number) {
            document.querySelectorAll('.seat-item').forEach(seat => {
                seat.classList.remove('selected');
            });
            let numDOM = document.querySelector(".seat-item:nth-child(2)")
            queryStmt = ".seat-item:nth-child("+number+")"
            
            let targetSeat = document.querySelector(queryStmt);
            targetSeat.classList.add('selected');
            let seatInput = document.getElementById('seatInput')
            console.log(seatInput)

            // 添加动画效果
            targetSeat.style.transform = 'scale(0.95)';
            setTimeout(() => {
                targetSeat.style.transform = 'scale(1)';
            }, 200);

            document.getElementById('selectedSeat').value = number;
            seatNumber = "座位: "+number
            document.getElementById('seatInput').value = seatNumber;

            updateSelectionDisplay();
        }

        // 更新显示信息
        function updateSelectionDisplay() {
            const seat = document.getElementById('selectedSeat').value;
            const classType = document.getElementById('selectedClass').value;
            console.log(classType);
            const price = document.getElementById('finalPriceValue').value;
            console.log(price);


            if(seat) {
                const classMap = {
                    economy: { name: '经济舱', color: 'text-primary' },
                    business: { name: '商务舱', color: 'text-success' },
                    first: { name: '头等舱', color: 'text-danger' }
                };
                const currentClass = classMap[classType];
                // console.log(currentClass.name);

                document.getElementById('displaySeat').textContent = seat;
                document.getElementById('displayClass').textContent = currentClass.name;
                document.getElementById('displayPrice').textContent = `¥ ` + price;
                document.getElementById('selectedCard').style.display = 'block';
            }
        }

        // 舱位选择处理
        document.querySelectorAll('.class-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.class-option').forEach(item => {
                    item.classList.remove('active');
                });
                this.classList.add('active');

                const basePrice = parseFloat(`${flight.price}`.replace(/,/g, '')); // 清理逗号并转为浮点数
                const classType = this.dataset.class?.toLowerCase(); // 统一转小写避免大小写问题
                const multiplier = {
                    economy: 1,
                    business: 1.5,
                    first: 3
                }[classType] || 1; // 默认值兜底

                // 计算并格式化最终价格
                const finalPrice = (basePrice * multiplier).toFixed(2); // 保留两位小数

                // 更新页面显示
                document.getElementById('displayPrice').textContent = `¥${finalPrice}`;
                document.getElementById('finalPriceValue').value = finalPrice;
                document.getElementById('selectedClass').value = classType;

                // 如果已选座位则更新显示
                if (document.getElementById('selectedSeat').value) {
                    updateSelectionDisplay();
                }
            });
        });

        // 表单验证
        function validateForm() {
            const seat = document.getElementById('selectedSeat').value;
            if (!seat) {
                alert('请选择座位号！');
                document.getElementById('seatInput').focus();
                return false;
            }
            if (seat < 1 || seat > 40) {
                alert('座位号必须在1-40之间！');
                return false;
            }
            return true;
        }

        // 初始化
        initSeats();
        document.querySelector('.class-option').click();

        // 座位下拉控制
        document.getElementById('seatInput').addEventListener('click', function() {
            document.getElementById('seatDropdown').style.display = 
                document.getElementById('seatDropdown').style.display === 'block' ? 'none' : 'block';
        });

        document.addEventListener('click', function(e) {
            if (!e.target.closest('.seat-select-wrapper')) {
                document.getElementById('seatDropdown').style.display = 'none';
            }
        });
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>